package com.project.util;

import com.alibaba.fastjson2.JSON;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ConvertBeanUtil {
      /**
       * 转换集合
       */
      public static <E, T> List<T> copyList(List<E> list, Class<T> clazz) {
            if (CollectionUtils.isEmpty(list) || clazz == null) {
                  return new ArrayList<>();
            }
            String oldOb = JSON.toJSONString(list);
            return JSON.parseArray(oldOb, clazz);
      }
      
      /**
       * 转换集合(进阶)
       */
      public static <E, T> List<T> copyList(List<E> list, Class<T> clazz, ConvertCallBack<E, T> convertCallBack) {
            if (CollectionUtils.isEmpty(list) || clazz == null) {
                  return new ArrayList<>();
            }
            return list.stream().map(e -> copy(e, clazz, convertCallBack)).collect(Collectors.toList());
      }
      
      /**
       * 转换对象
       */
      public static <E, T> T copy(Object ob, Class<T> clazz) {
            if (ob == null || clazz == null) {
                  return null;
            }
            String oldOb = JSON.toJSONString(ob);
            return JSON.parseObject(oldOb, clazz);
      }
      
      /**
       * 转换对象(进阶)
       */
      public static <E, T> T copy(E ob, Class<T> clazz, ConvertCallBack<E, T> convertCallBack) {
            if (ob == null || clazz == null) {
                  return null;
            }
            String oldOb = JSON.toJSONString(ob);
            T model = JSON.parseObject(oldOb, clazz);
            convertCallBack.converted(ob, model);
            return model;
      }
      
}
